package com.um.jdy.baofu.utils;

import cn.hutool.core.util.StrUtil;
import com.um.jdy.baofu.entity.account.PostFilesParmsEntity;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import java.io.FileInputStream;
import java.lang.reflect.Field;


/**
 * @author dasheng(大圣)
 * @date 2025/3/14 9:35
 * @Company www.baofu.com
 */
public class FormateParmsUtil
{
    public static HttpEntity formatepam(PostFilesParmsEntity pfpe){
        try {
            MultipartEntityBuilder builderParm = MultipartEntityBuilder.create();
            builderParm = ObjectNameValue(pfpe);
            if(pfpe.file != null){
                builderParm.addBinaryBody("file",new FileInputStream(pfpe.file),ContentType.APPLICATION_OCTET_STREAM,pfpe.file.getName());
            }
            return builderParm.build();
        }catch (Exception ex){
            return null;
        }
    }

    private static MultipartEntityBuilder ObjectNameValue(Object kvobject)throws Exception
    {
        Class<?> clazz = kvobject.getClass();
        Field[] fields = clazz.getDeclaredFields();
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (Field TempFiled :fields)
        {
            if(!StrUtil.isBlank(TempFiled.getName()))
            {
                String KeyNameStr = TempFiled.getName();
                TempFiled.setAccessible(true);
                try {
                    Object ValueObject =  TempFiled.get(kvobject);
                    builder.addTextBody(KeyNameStr,ValueObject.toString(), ContentType.TEXT_PLAIN);
                }catch (Exception ex){
                    builder.addTextBody(KeyNameStr,"", ContentType.TEXT_PLAIN);
                }
            }
        }
        return builder;
    }
}
